<template>
  <div class="home-container">
    <div class="banner-container">
      <img :src="require('../assets/home/banner.png')" alt="" />
    </div>
    <div class="theme-container">
      <div v-if="!isAuth">中国移动用户使用积分即可兑换</div>
      <div v-else>
        尊敬的用户，您当前积分为：<span>{{ points }}</span>
      </div>
    </div>
    <div class="middle-container">
      <div class="card-container">
        <div
          class="card-item"
          :class="[cardSelectIndex === index ? 'card-item-active' : '']"
          v-for="(item, index) in cardArr"
          :key="index"
          @click="cardClick(index)"
        >
          <div class="card-title">兑湘疆商城{{ item.shopScore }}积分</div>
          <div class="card-score">{{ item.mobileScore }}移动积分</div>
        </div>
      </div>
      <div>
        <!-- <Button v-if="!isAuth" title="立即兑换" @btnClick="btnLogin" /> -->
        <Button title="确认兑换" @btnClick="btnConfirm" />
      </div>
      <div class="explain-container">
        <div class="title-box">
          <img :src="require('../assets/home/tip_left.png')" alt="" />
          <div>活动说明</div>
          <img :src="require('../assets/home/tip_right.png')" alt="" />
        </div>
        <div class="explain-content">
          <p>
            1、本次活动将采用一次性兑换形式，现对应的积分只能选择相对应的积分档位。
          </p>
          <p>
            2、积分可兑换相应档位奖励，奖励不可换为货币用，如果有以上行为，将进行追责。
          </p>
          <p>3、本活动的一切解释权归。</p>
        </div>
      </div>
    </div>
    <StepMask
      :showMask="showMask"
      @closeMask="showMask = false"
      :orderData="orderData"
      :goodData="goodData"
    />
  </div>
</template>

<script>
import Button from "../components/Button.vue";
import StepMask from "../components/StepMask.vue";
import { queryAuth, createOrder } from "../api/home.js";
import { deepClone, isPhone } from "../utils/index";
export default {
  name: "Home",
  components: {
    Button,
    StepMask,
  },
  data() {
    return {
      isAuth: false,
      phone: "",
      points: null,
      usreid: "",
      cardSelectIndex: null,
      cardArr: [
        {
          mobileScore: 840,
          changyouScore: 700,
          shopScore: 5,
          // goodsid: "S9990193_bstSP10008",
          goodsid: 'XJYPSP100001'
        },
        {
          mobileScore: 1680,
          changyouScore: 1400,
          shopScore: 10,
          goodsid: 'XJYPSP100002'
        },
        {
          mobileScore: 2520,
          changyouScore: 2100,
          shopScore: 15,
          goodsid: 'XJYPSP100003'
        },
        {
          mobileScore: 4200,
          changyouScore: 3500,
          shopScore: 25,
          goodsid: 'XJYPSP100004'
        },
      ],
      goodData:{}, // 选中的商品详情 用来向子组件传参
      showMask: false,
      btnIsClicking: false,
      orderData: {},
    };
  },
  created() {
    if (this.$route.query.mobile && isPhone(this.$route.query.mobile)) {
      this.phone = this.$route.query.mobile;
      this._initPage();
    } else {
      this.$router.replace({ path: "/" });
    }
  },
  methods: {
    // 如果是测试环境就让所有的产品goodsid都为测试环境的goodsid
    _initTestGoods(){
      if (location.hostname === 'jtest.jinshanju.com') {
        this.cardArr.forEach(item=>{
          item.goodsid = 'S9990193_bstSP10008'
        })
        console.log('this.cardArr',this.cardArr)
      }
    },
    // seller 销售来源 1-001  platesource 对接平台分配  xiangjiangba  都是通过入口url带的参数
    // ?seller=1-001&platesource=xiangjiangba
    _initParams(){
      if (this.$route.query.seller) {
        this.$setSessionItem("seller", this.$route.query.seller);
      }
      if (this.$route.query.platesource) {
        this.$setSessionItem("platesource", this.$route.query.platesource);
      }
    },
    _initPage() {
      this._initParams()
      this._initTestGoods()
      // 防止取不到 seller
      setTimeout(()=>{
        this._queryAuth();
      },0)
    },
    _getCallBackUrl () {
      const url = `${location.href.split('/#/')[0]}/#/home?mobile=${this.phone}&seller=${this.$getSessionItem("seller")}&platesource=${this.$getSessionItem("platesource")}`
      return encodeURIComponent(url)
    },
    _queryAuth() {
      const mobileData = {
        mobile: this.phone,
        callbackUrl: this._getCallBackUrl()
      };
      /**
       * 返回：
            {
              "code": 10000,
              "msg": "ok",
              "data": {
                "authorize_url": "https://test-m-stg1.ppppoints.com/finance/profits/authPage/#/authorize?mobile=13651357217&outTokenId=240515743117639680&callbackUrl=https%3A%2F%2Fjifen.jinshanju.com%2Fchangyou%2Fauth_callback%3FoutTokenId%3D240515743117639680%26mobile%3D13651357217&partnerId=S9990193&channelSource=02000000&hmac=27a575c1ee5d3ac58864cc5026afa32e",
                "authorize_state": 1, //0-已经授权，1-未授权，如果未授权，请跳转到authorize_url，让用户进行授权。2-未绑定畅游，跳转到authorize_staticpage_url，进行绑定
                "authorize_staticpage_url": null,  //授权过度页面
                "points": 0, //用户积分
                "mobile": "136513571111”, //手机号
                "usreid": “240515743117639680” //用户id
              },
              "success": true
            }
       */
      queryAuth(mobileData).then((res) => {
        const { code, data, msg } = res.data;
        if (code === 10000) {
          // console.log(data);
          const {
            authorize_url,
            authorize_state,
            authorize_staticpage_url,
            points,
            usreid,
          } = data;
          if (authorize_state === 0) {
            this.isAuth = true;
            this.points = points || 0;
            this.usreid = usreid;
          } else if (authorize_state === 1) {
            window.location.href = authorize_url;
          } else if (authorize_state === 2) {
            window.location.href = authorize_staticpage_url;
          }
        } else {
          alert(msg);
        }
      });
    },
    _createOrder() {
      if (this.points === null) {
        alert('加载中,请稍后重试')
        return
      }
      if (this.cardSelectIndex === null) {
        alert('请选择一个积分兑换商品')
        return
      }
      if (this.points < this.goodData.mobileScore) {
        alert('积分不足')
        return
      }
      if (this.btnIsClicking){
        return
      }
      this.btnIsClicking = true
      const mobileData = {
        mobile: this.phone,
        goodsid: this.goodData.goodsid,
        sessionid: window.sessionId || '',
        fingerprint: window.fingerprint || ''
      };
      // 测试用的代码 不用反复创建订单了 上线后可以删除
      // let isTest = false
      // if (isTest) {
      //   const testData = {
      //     cmccMobile: "187****7512",
      //     goodOrderId: "202110280219001867",
      //     orderId: "21102816110217000671",
      //     outTokenId: "241269475879051264",
      //     points: 0,
      //     transTime: "20211028161108",
      //   };
      //   this.orderData = {
      //     ...testData,
      //     mobile: this.phone,
      //   };
      //   this.showMask = true;
      //   return
      // }
      createOrder(mobileData).then((res) => {
        const { code, data, msg } = res.data;
        if (code === 10000) {
          // console.log(data);
          const cloneData = deepClone(data.data);
          this.orderData = {
            ...cloneData,
            mobile: this.phone,
          };
          this.showMask = true;
        } else {
          alert(msg);
        }
        this.btnIsClicking = false
      });
    },
    cardClick(index) {
      if (this.cardSelectIndex == index) return;
      this.cardSelectIndex = index;
      this.goodData = this.cardArr[this.cardSelectIndex]
      sessionStorage.setItem('goodsid',this.goodData.goodsid)
    },
    btnConfirm() {
      this._createOrder();
    },
  },
};
</script>
<style lang="scss" scoped>
.home-container {
  width: 100%;
  min-height: 100%;
  background-color: #f8f9fa;
  .banner-container {
    width: 100%;
    img {
      width: 100%;
      display: block;
    }
  }
  .theme-container {
    padding: 0 15px;
    height: 50px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    font-size: 14px;
    background-color: #fff;
    color: #333;
    span {
      font-size: 15px;
      font-weight: bold;
      color: #fe5949;
    }
  }
  .middle-container {
    width: 100%;
    padding: 15px;
    box-sizing: border-box;
    .card-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      margin-bottom: 35px;
      .card-item {
        margin-bottom: 10px;
        background-color: #fff;
        width: 47%;
        padding: 15px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        border-radius: 5px;
        border: 1px solid transparent;
        box-shadow: 5px 5px 5px 5px #eee;
        &.card-item-active {
          border: 1px solid #ff7700;
          .card-title {
            color: #ff7700;
          }
          .card-score {
            color: #ff7700;
          }
        }
        .card-title {
          color: #333;
          font-size: 15px;
          line-height: 22px;
        }
        .card-score {
          color: #999;
          font-size: 12px;
        }
      }
    }
    .explain-container {
      margin-top: 45px;
      margin-bottom: 45px;
      width: 100%;
      padding: 10px 20px;
      box-sizing: border-box;
      background-color: #fff;
      border-radius: 5px;
      .title-box {
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 27px;
        }
        div {
          color: #333;
          font-size: 16px;
          margin: 0 10px;
        }
      }
      .explain-content {
        margin-top: 15px;
        margin-bottom: 20px;
        p {
          line-height: 25px;
          color: #333;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
